<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="费目名称" prop="costType">
            <vxe-select v-model="formData.costType" placeholder="请选择费目名称">
              <vxe-option
                v-for="dict in getStrDictOptions(DICT_TYPE.COST_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </vxe-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费目细项中文名" prop="cname">
            <el-input v-model="formData.cname" placeholder="请输入费目细项中文名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="费目细项英文名" prop="ename">
            <el-input v-model="formData.ename" placeholder="请输入费目细项英文名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计价单位" prop="unit">
            <vxe-select v-model="formData.unit" placeholder="请输入计价单位">
              <vxe-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PRICING_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </vxe-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="打印名称" prop="printName">
            <el-input v-model="formData.printName" placeholder="请输入费目细项打印名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效标识" prop="hasvalid">
            <el-switch
              v-model="formData.hasvalid"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              active-text="Y"
              inactive-text="N"
              active-value="Y"
              inactive-value="N"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="1"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #edit_cur="{ row }">
        <vxe-select v-model="row.fiCurrency" transfer>
          <vxe-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CURRENCY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </vxe-select>
      </template>
      <template #default_cur="{ row }">
        <span>{{ row.fiCurrency }}</span>
      </template>
      <template #edit_date="{ row }">
        <vxe-date-picker v-model="row.fiStartDate" />
      </template>
    </vxe-grid>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FeeApi, FeeVO } from '@/api/base/fee'
import { FeeItemApi } from '@/api/base/feeitem'
import {VxeUI, VxeGridProps, VxeGridInstance, type VxeGridListeners} from 'vxe-table'
import {DICT_TYPE, getStrDictOptions} from '@/utils/dict'
/** 费目 表单 */
defineOptions({ name: 'FeeForm' })
VxeUI.setConfig({
  zIndex: 3000
})
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

//费目
interface RowVO {
  id: number
  fiPrice: string
  fiCurrency: string
  fiStartDate: string
  fiEndDate: number
  fiRemark: string
}

const gridRef = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  showOverflow: true,
  keepSource: true,
  height: 400,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true
  },
  editRules: {
    fiPrice: [
      { required: true, message: '必须填写' }
    ],
    fiCurrency: [
      { required: true, message: '必须填写' }
    ],
    fiStartDate: [
      { required: true, message: '必须填写' }
    ],
    fiEndDate: [
      { required: true, message: '必须填写' }
    ]
  },
  toolbarConfig: {
    tools: [
      { name: '新增', code: 'add', status: 'primary' },
      { name: '删除', code: 'del', status: 'error' }
    ]
  },
  columns: [
    { type: 'checkbox', width: 60 },
    { type: 'seq', width: 70 },
    { field: 'fiPrice', title: '价格', editRender: { name: 'VxeNumberInput', props: { type: 'amount' } } },
    { field: 'fiCurrency', title: '币种', editRender: { }, slots: { edit: 'edit_cur', default: 'default_cur' } },
    { field: 'fiStartDate', title: '开始时间', editRender: { }, slots: { edit: 'edit_date' } },
    { field: 'fiEndDate', title: '结束时间', editRender: { name: 'VxeDatePicker', props: { type: 'date' } } },
    { field: 'fiRemark', title: '备注', editRender: { name: 'input' } }
  ],
  data: []
})

const gridEvents: VxeGridListeners = {
  toolbarToolClick({ code }) {
    switch (code) {
      case 'add':
        addEvent()
        break
    }
  }
}

const addEvent = async () => {
  const $grid = gridRef.value
  if ($grid) {
    const record = {
      name: `Name_${new Date().getTime()}`
    }
    const { row: newRow } = await $grid.insert(record)
    $grid.setEditRow(newRow)
  }
}

const fullValidEvent = async () => {
  const $grid = gridRef.value
  if ($grid) {
    const errMap = await $grid.validate(true)
    if (errMap) {
      VxeUI.modal.message({ status: 'error', content: '费目列表校验不通过！' })
      return
    }
  }
}

//旧表单

const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerUscc: undefined,
  costType: undefined,
  costName: undefined,
  fCode: undefined,
  cname: undefined,
  ename: undefined,
  unit: undefined,
  printName: undefined,
  hasvalid: 'Y',
  sort: undefined,
  deptId: undefined,
  list: []
})
const formRules = reactive({
  costType: [{ required: true, message: '费目名称不能为空', trigger: 'blur' }],
  fCname: [{ required: true, message: '费目细项中文名不能为空', trigger: 'blur' }],
  fEname: [{ required: true, message: '费目细项英文名不能为空', trigger: 'blur' }],
  fUnit: [{ required: true, message: '费目名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '费目名称不能为空', trigger: 'blur' }]

})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FeeApi.getFee(id)
      formData.value.cname = formData.value.fcname
      formData.value.ename = formData.value.fename
      formData.value.unit = formData.value.funit
      formData.value.printName = formData.value.fprintName
      formData.value.hasvalid = formData.value.fisvalid
      // 获取列表
      gridOptions.data = await FeeItemApi.getFeeItemList({
        fEname: formData.value.ename
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const $grid = gridRef.value
  // console.log(JSON.stringify($grid.getTableData().fullData))
  // return
  // 校验表单
  await formRef.value.validate()
  //校验列表
  await fullValidEvent()
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as FeeVO
    formData.value.list = $grid.getTableData().fullData
    const costData = getStrDictOptions(DICT_TYPE.COST_TYPE).find((item) => {
      return item.value == formData.value.costType
    })
    formData.value.costName = costData.label
    if (formType.value === 'create') {
      await FeeApi.createFee(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await FeeApi.updateFee(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerUscc: undefined,
    costType: undefined,
    costName: undefined,
    fCode: undefined,
    cname: undefined,
    ename: undefined,
    unit: undefined,
    printName: undefined,
    hasvalid: 'Y',
    sort: undefined,
    deptId: undefined,
    list: []
  }
  formRef.value?.resetFields()
}
</script>
